package gulimall.handler;

import gulimall.exception.BizCodeEnum;
import gulimall.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author HLF
 * @date 2022/5/1 14:50
 * gulimall全局异常处理类
 */
@RestControllerAdvice
@Slf4j
public class GulimallExceptionControllerAdvice {

    /**
     * 处理数据校验相关异常的异常处理方法
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题：{}，异常类型：{}", e.getMessage(), e.getClass());

        Map<String, String> map = new HashMap<>();
        e.getFieldErrors().forEach(fieldError -> {
            String defaultMessage = fieldError.getDefaultMessage();
            String field = fieldError.getField();
            map.put(field, defaultMessage);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),
                BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data", map);
    }

    //暂时注释掉，方便开发时找错误
    //@ExceptionHandler(value = {Throwable.class})
    public R handleUnknownException(Throwable throwable) {
        log.error("未知异常信息：{}，异常类型{}", throwable.getMessage(), throwable.getClass());

        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMessage());
    }
}
